package com.hbfk.entity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.hbfk.config.YinMaiUrlStatic;
import com.hbfk.util.BaseDao;
import com.hbfk.util.EncryptUtil;
import com.hbfk.util.HttpClient;
import com.hbfk.util.JedisUtil;
import com.hbfk.util.JsonBean;
import com.hbfk.util.ResponseFormat;
import com.hbfk.util.YinMaiMd5Util;

import redis.clients.jedis.Jedis;

public class DealUserToken {
	

	public static TblStaffUtil parseUserToken(String token) throws Exception {
		Jedis jedis = null; 	
		TblStaffUtil staff = null;
		String jsonStaff = null;
		try {
			if(token == null) {
				return null;
			}
			// login - username password --> userchecklogin -(jwt) - des --- 对称加密进行加密  token [staffid 用户编号]
			//                                              - 把用户 的信息存储到redis里面 [staffid 用户account] key : 87654321account:{userid:123,realname:张三}
			String staffId = EncryptUtil.getInstance().AESdecode(token,EncryptUtil.DESKEY);

			jedis = JedisUtil.getJedis();
			jsonStaff = jedis.get(staffId+JedisUtil.USERINFOKEY);
			if(jsonStaff == null) {
				return null;
			}
			staff = (TblStaffUtil) JSONObject.parseObject(jsonStaff,TblStaffUtil.class);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(jedis != null) {
				jedis.close();
			}
		}
		return staff;
	}

	public static JsonBean getYmTokenMothod(TblStaffUtil loginStaff) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Jedis jedis = null;
		HashMap<String,Object> resultMap = new HashMap<String,Object>(0);
		
		try {
			if(loginStaff.getPkYmStaffId() == null || "".equals(loginStaff.getPkYmStaffId())) {
				return ResponseFormat.retParam(0, 20008, null);
			}
			
			con = BaseDao.getInstance().getConnection();
			ps = con.prepareStatement("SELECT F_SECRETKEY FROM base_user WHERE F_ID = '"+loginStaff.getPkYmStaffId()+"'");
			rs = ps.executeQuery();
			String secretKey = null;
			while (rs.next()) {
				secretKey = rs.getString("F_SECRETKEY");
			}

			if(secretKey == null) {
				return ResponseFormat.retParam(0, 80002, null);
			}
			HashMap<String,String> filedMap = new HashMap<String,String>(0);
			
			filedMap.put("account", loginStaff.getUsername());
			
			//filedMap.put("password", YinMaiMd5Util.getStringMd5(YinMaiMd5Util.getStringMd5("hbyun@123456".toLowerCase()) + secretKey.toLowerCase()));
			filedMap.put("password", YinMaiMd5Util.getStringMd5(YinMaiUrlStatic.ymPassword).toLowerCase());
			filedMap.put("grant_type", "password");
			filedMap.put("client_id","admin");
			filedMap.put("client_secret", "123456");
			filedMap.put("scope", "all");
			
			Map<String, String> headerMap = new HashMap<>();
			headerMap.put("Content-Type","application/x-www-form-urlencoded");
			
			
			
			String result = HttpClient.httpPostLoginClient(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.singelSignUrl, filedMap,headerMap);
			
			if(result == null) {
				return ResponseFormat.retParam(0, 800002, null);
			}
			String ymToken = null;
			
			JSONObject reJson = JSONObject.parseObject(result);
			if("200".equals(reJson.getString("code"))) {
				JSONObject dataJson = reJson.getJSONObject("data");
				ymToken = dataJson.getString("token");
				jedis = JedisUtil.getJedis();
				loginStaff.setYmToken(ymToken);
			    jedis.set(loginStaff.getStaffid() + JedisUtil.USERINFOKEY, JSONObject.toJSONString(loginStaff));
				resultMap.put("ymToken", ymToken);
			}else {
				return ResponseFormat.retParam(0, 40001, null);
			}
		}finally{
			BaseDao.getInstance().close(con,rs,ps);
		}
		 return ResponseFormat.retParam(1, 200, resultMap);
	}

	public static String dealYmUrlMethod(String url, HashMap<String, Object> filedMap,
			Map<String, String> headerMap, TblStaffUtil loginStaff, String type) throws Exception {
		String result = null;
		
		switch (type) {
		case "put":
			result = HttpClient.httpPutClient(url, filedMap,headerMap);
			break;
		case "post":
			result = HttpClient.httpPostClient(url, filedMap,headerMap);
			break;
		case "get":
			result = HttpClient.httpGetClient(url, filedMap,headerMap);
			break;
		default:
			break;
		}
		
		if(result == null) {
			return null;
		}
		
		JSONObject reJson = JSONObject.parseObject(result);
		if("600".equals(reJson.getString("code"))) {
			JsonBean jsonBean = getYmTokenMothod(loginStaff);
			JSONObject json = JSONObject.parseObject(jsonBean.getData().toString());
			String ymToken = json.getString("ymToken");
			System.out.println("登录过期，重新登录获取token："+ymToken);
			headerMap.put("Authorization", ymToken);
			result = dealYmUrlMethod(url,filedMap,headerMap,loginStaff,type);
			return result;
		}else if(!"200".equals(reJson.getString("code"))){
			System.out.println("接口调用失败！");
			return null;
		}
		
		return result;
	}

}
